package cn.edu.ncut.cs.springboot.springbootdatabase.service.impl;

import cn.edu.ncut.cs.springboot.springbootdatabase.dao.AccountRepository;
import cn.edu.ncut.cs.springboot.springbootdatabase.entity.Account;
import cn.edu.ncut.cs.springboot.springbootdatabase.service.AccountService;
import jakarta.annotation.Resource;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class AccountServiceImpl implements AccountService {
    @Resource
    private AccountRepository accountRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Account account = this.findAccountByName(username);
        if(account == null)
            throw  new UsernameNotFoundException("用户名或密码错误");
        return User
                .withUsername(username)
                .password(account.getPassword())
                .roles(account.getRole())
                .build();
    }
    @Override
    public Account findAccountByName(String text) {
        return accountRepository.findByUsername(text);
    }
    @Override
    public void deleteUsername(String name) {
        // 使用AccountRepository提供的方法，根据name查找对应的Account对象并删除
        // 这里假设Account表中有一个name字段用于关联，具体根据实际表结构调整哦
        accountRepository.deleteByUsername(name);
    }
    @Override
    public void saveAccount(Account account) {
        accountRepository.save(account);
    }
}
